package com.ugoodtech.mdcc.web.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.service.StationTechColorReportService;
import com.ugoodtech.mdcc.web.service.UserLogService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class StationTechColorReportServiceImpl implements StationTechColorReportService {

    private static final Logger logger = LoggerFactory.getLogger(StationTechColorReportServiceImpl.class);

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private AuditReportRepository auditReportRepository;

    @Autowired
    private AuditColorReportRepository auditColorReportRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private AuditReportRecorderRepository auditReportRecorderRepository;

    @Autowired
    private UserLogRepository userLogRepository;

    @Autowired
    private UserLogService userLogService;

    @Override
    public JsonResponse auditTrue(User user, Long reportId,Integer userType) {
        AuditReport auditReport = auditReportRepository.findOne(reportId);
        if (auditReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "报告不存在");
        }
        UserProfile managerUser = userProfileRepository.findByUserId(user.getId());
        if (managerUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登录用户");
        }
        List<AuditColorReport> colorReports = auditColorReportRepository.selectAnswer(reportId);
        for (AuditColorReport report : colorReports){
            if (report.getQuestionId() == 175L){
                List<Station> stationNumList = stationRepository.findByStationNameList(report.getAnswerOther());
                if (!stationNumList.isEmpty()) {
                    if (auditReport.getStation() != null && !auditReport.getStation().getName().equals(report.getAnswerOther())) {
                        return JsonResponse.errorResponseWithError("抱歉", "维修站名称重复了");
                    }
                }
            }else if (report.getQuestionId() == 181L){
                //验证维修站编号是否已经存在
                List<Station> stationNumList = stationRepository.findByStationNumList(report.getAnswerOther());
                if (!stationNumList.isEmpty()) {
                    if (auditReport.getStation() != null && !auditReport.getStation().getStationNum().equals(report.getAnswerOther())) {
                        return JsonResponse.errorResponseWithError("抱歉", "维修站编号重复了");
                    }
                }
            }
        }
        if (auditReport.isReAudit()) {
            logger.info("是重复提交的报告");
            Station station = auditReport.getStation();
            if (station.getReport_finished()==0){
                station.setReport_finished(userType+1);
            }else if((station.getReport_finished() == 1 && userType == 1)||(station.getReport_finished() == 2 && userType == 0)){
                station.setReport_finished(3);
            }
            User reUser = null;
            AuditColorReport departmentAnswer = null;
            UserProfile userProfile = new UserProfile();
            for (AuditColorReport report : colorReports){
                if (report != null && report.getQuestionId() != null) {
                    switch (report.getQuestionId().intValue()){
                        case 175:
                            logger.info("查询维修站名称");
                            station.setName(report.getAnswerOther());
                            break;
                        case 173:
                            logger.info("查询维修站省份");
                            station.setProvince(report.getAnswerOther());
                            break;
                        case 174:
                            logger.info("查询维修站城市");
                            station.setCity(report.getAnswerOther());
                            break;
                        case 186:
                            logger.info("查询维修站地址");
                            station.setAddress(report.getAnswerOther());
                            break;
                        case 4:
                            reUser = userRepository.findByUsername(report.getAnswerOther());
                            if (reUser == null) {
                                reUser = new User();
                                reUser.setUsername(report.getAnswerOther());
                                reUser.setUserType(UserType.customer);
                                reUser.setPassword(passwordEncoder.encode(Constants.INIT_PASSWORD));
                                reUser.setUserFlag(1);
                            } else {
                                if (reUser.getUserFlag() != 1){
                                    reUser.setUserFlag(2);
                                }
                                if (reUser.getUserType().equals(UserType.insiders)){
                                    return JsonResponse.errorResponseWithError("抱歉", "该人员是内部人员无法作为维修站联系人");
                                }
                                userProfile = userProfileRepository.findByUserId(reUser.getId());
                                if (null == userProfile) {
                                    userProfile = new UserProfile();
                                }
                            }

                            logger.info("set User信息");

                            userRepository.save(reUser);
                            logger.info("保存User成功");
                            station.setUser(reUser);

                            logger.info("setUserProfile信息");
                            userProfile.setUser(reUser);
                            userProfile.setTelephone(report.getAnswerOther());
                            managerUser = userProfileRepository.findByUserId(user.getId());
                            userProfile.setAddUser(managerUser);
                            break;
                        case 2:
                            logger.info("查询联系人姓名");
                            station.setContact(report.getAnswerOther());
                            userProfile.setRealName(report.getAnswerOther());
                            break;
                        case 3:
                            logger.info("查询联系人职位");
                            userProfile.setPosition(report.getAnswerOther());
                            break;
                        case 8:logger.info("查询维修站品牌");
                            String[] brandIds = report.getAnswerId().split(",");
                            StringBuffer stringBuffer = new StringBuffer("");
                            for (String id : brandIds) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                                if (id.equals("369")) {
                                    stringBuffer.append(report.getAnswerOther() + ",");
                                } else {
                                    if (answerOption.getName()!=null&&answerOption.getName()!=null) {
                                        stringBuffer.append(answerOption.getName() + ",");
                                    }
                                }
                            }
                            station.setBrand(stringBuffer.toString());
                            break;
                        case 184:logger.info("查询客户状态");
                            if (StringUtils.isNotEmpty(report.getAnswerId())) {
                                station.setCustomerStat(Long.valueOf(report.getAnswerId()));
                            }
                            break;
                        case 185:
                            logger.info("查询客户类型");
                            if (StringUtils.isNotEmpty(report.getAnswerId())) {
                                station.setCustomerType(Long.valueOf(report.getAnswerId()));
                            }
                            break;
                        case 13:
                            logger.info("查询油漆品牌");
                            if (StringUtils.isNotEmpty(report.getAnswerId())) {
                                station.setPaintBrand(report.getAnswerId());
                            }
                            break;
                        case 182:
                            logger.info("查询品牌定位");
                            if (StringUtils.isNotEmpty(report.getAnswerId())) {
                                station.setProductPosition(report.getAnswerId());
                            }
                            break;
                        case 7:
                            logger.info("查询维修站类型");
                            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(report.getAnswerId()));
                            station.setCategory(answerOption.getName());
                            report.setAnswerOther(answerOption.getName());
                            auditColorReportRepository.save(report);
                            break;
                        case 181:
                            logger.info("查询维修站编号");
                            station.setStationNum(report.getAnswerOther());
                            break;
                        case 14:
                            departmentAnswer = report;
                            break;
                    }
                }
            }
            stationRepository.save(station);
            auditReport.setStation(station);
            auditReport.setAuditing(Constants.AUDIT_TRUE);
            auditReport.setReAudit(false);
            try {
                //先保存维修站
                station.setOtherBrand(auditReport.isOtherBrnad());
                station.setColorReportId(reportId);
                station.setCheckStation(true);
                stationRepository.save(station);
                logger.info("查询经销商");
                if (departmentAnswer != null && StringUtils.isNotEmpty(departmentAnswer.getAnswerOther())) {
                    Department department = departmentRepository.selectByName(departmentAnswer.getAnswerOther());
                    if (department != null) {
                        List<Station> stationList = department.getStationList();
                        if (stationList != null && stationList.size() > 0) {
                            stationList.add(station);
                        } else {
                            stationList = new ArrayList<>();
                            stationList.add(station);
                        }
                        department.setStationList(stationList);
                        departmentRepository.save(department);
                    }
                }
                //在保存用户
                userRepository.save(reUser);
                //再设置维修站的联系人
                station.setUser(reUser);
                station.setDeleted(false);
                station.setEnabled(true);
                stationRepository.save(station);
                //保存报告
                auditReportRepository.save(auditReport);
                //保存用户索关联的维修站ID
                reUser.setStationId(station.getId());
                userRepository.save(reUser);
                //最后将用户详情与用户关联
                userProfile.setUser(reUser);
                userProfileRepository.save(userProfile);
                AuditReportRecorder auditReportRecorde = new AuditReportRecorder();
                auditReportRecorde.setAuditReport(auditReport);
                auditReportRecorde.setTrue_false(true);
                auditReportRecorde.setUser(user);
                auditReportRecorderRepository.save(auditReportRecorde);
                return updateColorReport(auditReport.getId(), station, user);
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResponse.errorResponseWithError("抱歉", "审核失败，请重试");
            }

        }

        Station station = new Station();
        UserProfile userProfile = new UserProfile();
        User user1 = null;
        AuditColorReport departmentReport = null;
        for (AuditColorReport report : colorReports){
            if (report != null && report.getQuestionId() != null) {
                switch (report.getQuestionId().intValue()){
                    case 181: {
                        station.setStationNum(report.getAnswerOther());
                    }
                        break;
                    case 175:
                        if (auditReport.getStation() != null) {
                            station = auditReport.getStation();
                        }
                        station.setReport_finished(userType + 1);
                        if (report != null) {
                            logger.info("设置维修站名称");
                            station.setName(report.getAnswerOther());
                        } else {
                            station.setName("");
                        }
                        logger.info("设置维修站省份");
                        break;
                    case 173:
                        station.setProvince(report.getAnswerOther());
                        logger.info("设置维修站城市");
                        break;
                    case 174:
                        station.setCity(report.getAnswerOther());
                        logger.info("查询维修站地址");
                        break;
                    case 186:
                        station.setAddress(report.getAnswerOther());
                        break;
                    case 4:
                        logger.info("开始新建UserProfile");
                        logger.info("查询联系人手机");
                        String phone = report.getAnswerOther();
                        user1 = userRepository.findByUsername(phone);
                        if (user1 == null) {
                            user1 = new User();
                            user1.setUsername(report.getAnswerOther());
                            user1.setUserType(UserType.customer);
                            user1.setPassword(passwordEncoder.encode(Constants.INIT_PASSWORD));
                            user1.setUserFlag(1);
                        } else {
                            if (user1.getUserFlag() != 1){
                                user1.setUserFlag(2);
                            }
                            if (user1.getUserType().equals(UserType.insiders)){
                                return JsonResponse.errorResponseWithError("抱歉", "该人员是内部人员无法作为维修站联系人");
                            }
                            userProfile = userProfileRepository.findByUserId(user1.getId());
                        }
                        //在保存用户
                        userRepository.save(user1);
                        userProfile.setTelephone(report.getAnswerOther());
                        userProfile.setAddUser(managerUser);
                        break;
                    case 2:
                        station.setContact(report.getAnswerOther());
                        userProfile.setRealName(report.getAnswerOther());
                        break;
                    case 3:
                        userProfile.setPosition(report.getAnswerOther());
                        break;
                    case 8:
                        String[] brandIds = report.getAnswerId().split(",");
                        StringBuffer stringBuffer = new StringBuffer("");
                        for (String id : brandIds) {
                            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                            if (id.equals("369")) {
                                stringBuffer.append(report.getAnswerOther() + ",");
                            } else {
                                if (answerOption.getName()!=null&&answerOption.getName()!=null) {
                                    stringBuffer.append(answerOption.getName() + ",");
                                }
                            }
                        }
                        station.setBrand(stringBuffer.toString());
                        report.setAnswerOther(report.getAnswerOther());
                        auditColorReportRepository.save(report);
                        break;
                    case 184:
                        logger.info("查询客户状态");
                        if (StringUtils.isNotEmpty(report.getAnswerId())) {
                            station.setCustomerStat(Long.valueOf(report.getAnswerId()));
                        }
                        break;
                    case 185:
                        logger.info("查询客户类型");
                        if (StringUtils.isNotEmpty(report.getAnswerId())) {
                            station.setCustomerType(Long.valueOf(report.getAnswerId()));
                        }
                        break;
                    case 13:
                        logger.info("查询油漆品牌");
                        if (StringUtils.isNotEmpty(report.getAnswerId())) {
                            station.setPaintBrand(report.getAnswerId());
                        }
                        break;
                    case 182:
                        logger.info("查询品牌定位");
                        if (StringUtils.isNotEmpty(report.getAnswerId())) {
                            station.setProductPosition(report.getAnswerId());
                        }
                        break;
                    case 7:
                        if (StringUtils.isEmpty(report.getAnswerId())) {
                            station.setCategory("");
                        } else {
                            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(report.getAnswerId()));
                            if (answerOption != null) {
                                station.setCategory(answerOption.getName());
                            } else {
                                station.setCategory("");
                            }
                        }
                        break;
                    case 14:
                        departmentReport = report;
                        break;
                }
            }
        }
        auditReport.setStation(station);
        auditReport.setAuditing(Constants.AUDIT_TRUE);
        try {
            //先保存维修站
            station.setColorReportId(reportId);
            if (auditReport.isSupplement()) {
                station.setCheckStation(false);
            } else {
                station.setCheckStation(true);
            }
            station.setOtherBrand(auditReport.isOtherBrnad());
            stationRepository.save(station);
            logger.info("查询经销商");
            if (departmentReport != null && StringUtils.isNotEmpty(departmentReport.getAnswerOther())) {
                Department department = departmentRepository.selectByName(departmentReport.getAnswerOther());
                if (department != null) {
                    List<Station> stationList = department.getStationList();
                    if (stationList != null && stationList.size() > 0) {
                        stationList.add(station);
                    } else {
                        stationList = new ArrayList<>();
                        stationList.add(station);
                    }
                    department.setStationList(stationList);
                    departmentRepository.save(department);
                }
            }
            //再设置维修站的联系人
            station.setUser(user1);
            station.setDeleted(false);
            station.setEnabled(true);
            stationRepository.save(station);
            //保存报告
            auditReportRepository.save(auditReport);
            //保存用户索关联的维修站ID
            user1.setStationId(station.getId());
            userRepository.save(user1);
            //最后将用户详情与用户关联
            userProfile.setUser(user1);
            userProfileRepository.save(userProfile);

            AuditReportRecorder auditReportRecorde = new AuditReportRecorder();
            auditReportRecorde.setAuditReport(auditReport);
            auditReportRecorde.setTrue_false(true);
            auditReportRecorde.setUser(user);
            auditReportRecorderRepository.save(auditReportRecorde);
            return updateColorReport(auditReport.getId(), station, user);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("抱歉", "审核失败，请重试");
        }
    }

    private JsonResponse updateColorReport(Long auditReportId, Station station, User user) {
        AuditReport auditReport = auditReportRepository.findOne(auditReportId);
        QAuditColorReport qAuditColorReport = QAuditColorReport.auditColorReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qAuditColorReport.deleted.eq(false));
        builder.and(qAuditColorReport.enabled.eq(true));
        builder.and(qAuditColorReport.auditReport.id.eq(auditReportId));
        List<AuditColorReport> auditColorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);

        QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
        builder = new BooleanBuilder();
        builder.and(qStationColorReport.deleted.eq(false));
        builder.and(qStationColorReport.enabled.eq(true));
        builder.and(qStationColorReport.stationReport.station.id.eq(auditReport.getStation().getId()));
        List<StationColorReport> stationColorReportList = (List<StationColorReport>) stationColorReportRepository.findAll(builder);
        if (stationColorReportList == null || stationColorReportList.size() <= 0) {
            StationReport stationReport = new StationReport();
            stationReport.setAuditing(Constants.AUDIT_TRUE);
            stationReport.setStation(auditReport.getStation());
            stationReport.setCategory(Constants.TECHCOLOR_REPORT);
            stationReport.setReportType(Constants.REPORT_TYPE_COMPLETE);
            stationReport.setUser(auditReport.getUser());
            stationReportRepository.save(stationReport);
            for (AuditColorReport report : auditColorReportList) {
                StationColorReport colorReport = new StationColorReport(report);
                colorReport.setStationReport(stationReport);
                stationColorReportRepository.save(colorReport);
            }
        } else {
            StationReport stationReport = null;
            for (AuditColorReport auditColorReport : auditColorReportList) {
                for (StationColorReport stationColorReport : stationColorReportList) {
                    if (auditColorReport.getQuestionId().equals(stationColorReport.getQuestionId())) {
                        stationReport = stationColorReport.getStationReport();
                        stationColorReport.setAnswerPhoto(auditColorReport.getAnswerPhoto());
                        stationColorReport.setAnswerOther(auditColorReport.getAnswerOther());
                        stationColorReport.setAnswerId(auditColorReport.getAnswerId());
                        stationColorReportRepository.save(stationColorReport);
                    }
                    StationColorReport colorReport = stationColorReportRepository.selectReport(stationReport.getId(), auditColorReport.getQuestionId());
                    if (colorReport == null) {
                        StationColorReport report = new StationColorReport(auditColorReport);
                        report.setStationReport(stationReport);
                        stationColorReportRepository.save(report);
                    }
                }
            }
            stationReport.setAuditing(Constants.AUDIT_TRUE);
            stationReport.setUser(auditReport.getUser());
            Date date = new Date();
            auditReport.setUpdateTime(date);
            auditReport.setUpdateTimeStr(new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(date));
            auditReportRepository.save(auditReport);
            stationReportRepository.save(stationReport);
        }
        updateLogUser(auditReportId, station, user);
        return JsonResponse.successResponse();
    }


    /**
     * 将station设置进日志
     *
     * @param auditReportId
     * @param station
     */
    private void updateLogUser(Long auditReportId, Station station, User user) {
        UserLog confirmUserLog = userLogService.addUserLog(user, null, auditReportId, Constants.CUSTOMER_REPORT, LogConstants.operate_type_confirm, LogConstants.business_type_color_report, null, null);
        if (null != station) {
            confirmUserLog.setStationName(station.getName());
            confirmUserLog.setStationNo(station.getStationNum());
            userLogRepository.save(confirmUserLog);
        }
        AuditColorReport auditColorReport = auditColorReportRepository.selectReport(auditReportId, 175L);
        if (null != auditColorReport && StringUtils.isNotEmpty(auditColorReport.getAnswerOther())) {
            QUserLog qUserLog = QUserLog.userLog;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qUserLog.deleted.eq(false));
            builder.and(qUserLog.enabled.eq(true));
            builder.and(qUserLog.reportId.eq(auditReportId));
            builder.and(qUserLog.category.eq(Constants.CUSTOMER_REPORT));
//            builder.and(qUserLog.station.isNull());
//            builder.and(qUserLog.stationName.eq(auditColorReport.getAnswerOther()));
            List<UserLog> userLogList = (List<UserLog>) userLogRepository.findAll(builder);
            for (UserLog userLog : userLogList) {
                userLog.setStation(station);
                userLogRepository.save(userLog);
            }
        }
    }

    @Override
    public JsonResponse auditFalse(User user, Long reportId, String auditNote) {
        AuditReport stationColorReport = auditReportRepository.findOne(reportId);
        if (stationColorReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "报告不存在");
        }
        stationColorReport.setAuditing(Constants.AUDIT_FALSE);
        stationColorReport.setAuditNote(auditNote);

        StationReport stationReport = null;
        if (stationColorReport.getStation() != null && stationColorReport.getStation().isCheckStation() == true) {
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.station.id.eq(stationColorReport.getStation().getId()));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            stationReport = stationReportRepository.findOne(builder);
            if (stationReport == null) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到此维修站原有信息");
            }
            stationReport.setAuditing(Constants.AUDIT_TRUE);
        }
        try {
            if (stationReport != null) {
                stationReportRepository.save(stationReport);
            }
            auditReportRepository.save(stationColorReport);
            AuditReportRecorder auditReportRecorde = new AuditReportRecorder();
            auditReportRecorde.setAuditReport(stationColorReport);
            auditReportRecorde.setTrue_false(false);
            auditReportRecorde.setUser(user);
            auditReportRecorde.setNote(auditNote);
            auditReportRecorderRepository.save(auditReportRecorde);
            return JsonResponse.successResponse();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("抱歉", "审核失败，请重试");
        }
    }


}
